from django.http import HttpResponse
from django.shortcuts import render
from .models import Author, Book


# Create your views here.

def add_author(request):
    Author.objects.create(name='author3', age=18)
    return HttpResponse("Hello, world.")


def add_book(request):
    book = Book.objects.create(name='book2', price=100)
    author1 = Author.objects.filter(id=2).first()
    author2 = Author.objects.filter(id=3).first()
    book.authors.add(author1, author2)
    book.save()
    return HttpResponse("Hello, world.")


def delete_author(request):
    Author.objects.filter(id=1).delete()
    return HttpResponse("Hello, world.")


def delete_book(request):
    Book.objects.filter(id=1).delete()
    return HttpResponse("Hello, world.")


def select_book(request):
    book = Book.objects.filter(id=2).first()
    print(book.name, book.price)
    authors = book.authors.all()
    for author in authors:
        print(author.name, author.age)

    return HttpResponse("Hello, world.")


def select_author(request):
    author = Author.objects.filter(id=2).first()
    print(author.name, author.age)
    # 反向关联
    books = author.book_set.all()
    for book in books:
        print(book.name, book.price)

    return HttpResponse("Hello, world.")
